package lt.vu.mif.os.codereader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.Exception;
import java.util.logging.Level;
import java.util.logging.Logger;
import lt.vu.mif.os.memory.UserMemory;
import lt.vu.mif.os.memory.Word;
import lt.vu.mif.os.provider.Constants;
/**
* Codereader class which reads code and puts into user memory cells
* 
* @author Antanas Rudaitis
* @author Laurynas Paradauskas
* @author Algirdas Šaltupis
* 
*/
public class CodeReader implements Constants {
    private FileReader file;
    private BufferedReader source;
    public boolean check;
/**
 * CodeReader() constructor reads program code and puts into user memory
 * @param f Program source code which will be executed
 *
 */
    public CodeReader(String f, int id) {
        try {
            int i = 0;
            file = new FileReader(f);
            source = new BufferedReader(file);
            String line = source.readLine();
            while (line != null) {
                if (line.length() > 4) {
                    line = line.substring(0,wordSize);
                }
                UserMemory.setValue(i+id*Constants.vmMemSize, new Word(line));
                //System.out.println(UserMemory.memory[i]);
                line = source.readLine();
                i++;
                check = true;
                if (i > vmMemCodeSize) { check = false; break; }
            }
           // System.out.println(index);
        }
        catch (Exception e) {
            e.printStackTrace();
            //System.out.println(e.printStackTrace());
        }
    }

    public void closeFile() {
      try {
        source.close();
        file.close();
      }
      catch (IOException ex) {
        Logger.getLogger(CodeReader.class.getName()).log(Level.SEVERE, null, ex);
      }
      
    }

    public String getLine() {
      try {
        return source.readLine();
      }
      catch (IOException ex) {
        Logger.getLogger(CodeReader.class.getName()).log(Level.SEVERE, null, ex);
        return null;
      }
    }
}
